<?php
class Post extends AppModel {

    public $recursive = -1;
    public $name = 'Post';
    public $validate = array('title' => array('notempty'));

    // The Associations below have been created with all possible keys,
    // Those that are not needed can be removed
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        ),
        'PostTerm' => array(
            'className' => 'PostTerm',
            'foreignKey' => 'post_term_id',
            'counterCache' => true,
            'dependent' => true
        )
    );

    public $hasMany = array(
        'Attachment' => array(
            'className' => 'Media.Attachment',
            'foreignKey' => 'foreign_key',
            'conditions' => array('Attachment.model' => 'Post'),
            'dependent' => true
        )
    );
    
    /* We have to mannualy update the attachment count in Posts table */
    public function afterSave($created){
        if(!$created){
            $this->query("
                UPDATE posts 
                SET attachment_count=(
                    SELECT COUNT(id) FROM attachments
                    WHERE foreign_key={$this->id} AND model='Post')
                WHERE id={$this->id}");
        }
        return true;
    }
    
    public function get_attachment($id=null){
        if(!$id){
            return false;
        }
        $this->Attachment->recursive = -1;
        return $this->Attachment->read(null, $id);
    }

}
?>
